package com.atguigu.fink.chapter01.sql;

import com.atguigu.fink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @Author lzc
 * @Date 2022/11/28 09:06
 */
public class Flink01_SQL_BaseUse_1 {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("s1", 1L, 10),
            new WaterSensor("s1", 2L, 10),
            new WaterSensor("s2", 3L, 20),
            new WaterSensor("s1", 4L, 30),
            new WaterSensor("s1", 5L, 40),
            new WaterSensor("s1", 6L, 50)
        );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        Table table = tEnv.fromDataStream(stream);
        // 使用 sql 语句在 table 对象上执行查询
        // 1. 在未注册的表上执行查询
        // 执行 sql 语句的地方
        //tEnv.executeSql("sql语句: ddl语句和增删改");
        //tEnv.sqlQuery("sql语句: 查询语句");
        // Table result = tEnv.sqlQuery("select * from " + table + " where id='s1'");
        // 2. 在已经注册的表上执行查询
        // 注册一个临时表
        tEnv.createTemporaryView("sensor", table);
//        Table result = tEnv.sqlQuery("select * from sensor where id='s1'");
        Table result = tEnv.sqlQuery("select id, sum(vc) vc_sum from sensor group by id");
        result.execute().print();
        
        
    }
}
